package com.dd.stack.se.stream.concurrent.reentrantlock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author liuxianmeng
 * @CreateTime 2025/9/28 15:07
 * @Description 类功能作用说明
 */
public class InterruptibleLockExample {
    private final ReentrantLock lock = new ReentrantLock();

    public void doTask() throws InterruptedException {
        // tryLock() 尝试获取锁，支持中断
        if (lock.tryLock()) { // 也可使用 lock.lockInterruptibly() 直接响应中断
            try {
                System.out.println(Thread.currentThread().getName() + " 获取锁，执行任务");
                Thread.sleep(3000); // 模拟任务执行
            } finally {
                lock.unlock();
            }
        } else {
            System.out.println(Thread.currentThread().getName() + " 未获取到锁，放弃执行");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        InterruptibleLockExample example = new InterruptibleLockExample();
        Thread t1 = new Thread(() -> {
            try {
                example.doTask();
            } catch (InterruptedException e) {
                System.out.println("t1 被中断");
            }
        }, "t1");

        Thread t2 = new Thread(() -> {
            try {
                example.doTask();
            } catch (InterruptedException e) {
                System.out.println("t2 被中断");
            }
        }, "t2");

        t1.start();
        Thread.sleep(100); // 确保t1先获取锁
        t2.start();
        t2.interrupt(); // 中断t2的等待
    }
}
